<?php


namespace app\api\server;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;


class Token
{

    private  $key = "mini-program-api";

    /**
     * 生成令牌
     * @param $uid
     * @return string
     */
    public static function createToken($uid){
        $payload = [
            'iss' => 'http://example.org',
            'aud' => 'http://example.com',
            'iat' => time(),
            'nbf' => time(),
            'expire' => time() + 86400,
            'uid' => $uid
        ];

        /**
         * IMPORTANT:
         * You must specify supported algorithms for your application. See
         * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
         * for a list of spec-compliant algorithms.
         */
        return JWT::encode($payload, (new self())->key, 'HS256');


    }

    /**
     * 验证token
     * @return false|mixed
     */
    public static function verifyToken(){
        try {
            if (!isset($_SERVER["HTTP_AUTHORIZATION"])) {
                return  false;
            }

            $token = $_SERVER["HTTP_AUTHORIZATION"];

            if (is_numeric(strrpos($token,"Bearer"))) {
                $token = trim(str_replace("Bearer"," ",$token));
            }

            if (empty($token)) {
                return  false;
            }
            $decoded = JWT::decode($token, new Key((new self())->key, 'HS256'));

            $decoded = (array)$decoded;
            if (!isset($decoded['uid']) && $decoded['expire'] < time()) {
                return false;
            }
            return $decoded['uid'];
        }catch (\Exception $exception){
            return  false;
        }

    }
}